package com.liujun.microserver.auth2.refreshtoken.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * 授权服务配制
 * 
 * @author liujun
 * @date 2018年6月30日
 */
@Configuration
@EnableAuthorizationServer
public class Auth2AuthorizeationServer extends AuthorizationServerConfigurerAdapter {

	/**
	 * 用户认证的manager
	 */
	@Autowired
	private AuthenticationManager authenticationManager;

	protected UserDetailsService userDetailsService() {
		InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
		manager.createUser(User.withUsername("user_1").password("112233").authorities("USER").build());
		manager.createUser(User.withUsername("user_2").password("123456").authorities("USER").build());
		return manager;
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.authenticationManager(authenticationManager);
		endpoints.userDetailsService(userDetailsService());
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory()
				// 客户端的名称
				.withClient("clientapp")
				// 客户端安全码
				.secret("112233")
				// 重定向的url
				.redirectUris("http://localhost:9001/callback")
				// 指定为刷新授权码模式
				.authorizedGrantTypes("refresh_token", "password")
				// 刷新的toker过期
				.refreshTokenValiditySeconds(300)
				// 细分权限
				.scopes("read_userinfo", "read_contacts");

	}

}
